<template>
  <view class="container">
    <!-- 表单 -->
    <view class="form-container" v-if="formLoaded">
      <!-- 基本信息 -->
      <view class="form-section">
        <view class="section-title">
          <text>基本信息</text>
        </view>
        
        <view class="form-item">
          <text class="form-label">农作物</text>
          <text class="form-value">{{ cropName }}</text>
        </view>
        
        <view class="form-item">
          <text class="form-label required">记录日期</text>
          <picker 
            mode="date" 
            :value="recordDateStr" 
            @change="onRecordDateChange"
          >
            <view class="picker">
              <text>{{ recordDateStr || '请选择记录日期' }}</text>
              <uni-icons type="right" size="14" color="#cccccc"></uni-icons>
            </view>
          </picker>
        </view>
        
        <view class="form-item">
          <text class="form-label required">生长阶段</text>
          <picker 
            mode="selector" 
            :range="growthStages" 
            @change="onGrowthStageChange"
            :value="growthStageIndex"
          >
            <view class="picker">
              <text>{{ recordForm.growth_stage || '请选择生长阶段' }}</text>
              <uni-icons type="right" size="14" color="#cccccc"></uni-icons>
            </view>
          </picker>
        </view>
      </view>
      
      <!-- 生长数据 -->
      <view class="form-section">
        <view class="section-title">
          <text>生长数据</text>
        </view>
        
        <view class="form-item">
          <text class="form-label">植株高度(cm)</text>
          <input 
            class="form-input" 
            v-model="recordForm.height" 
            type="digit"
            placeholder="请输入植株高度"
          />
        </view>
        
        <view class="form-item">
          <text class="form-label">叶片数量</text>
          <input 
            class="form-input" 
            v-model="recordForm.leaf_count" 
            type="number"
            placeholder="请输入叶片数量"
          />
        </view>
        
        <view class="form-item">
          <text class="form-label">健康状况</text>
          <picker 
            mode="selector" 
            :range="healthOptions" 
            range-key="label"
            @change="onHealthChange"
            :value="healthIndex"
          >
            <view class="picker">
              <text :class="getHealthClass(recordForm.health_status)">{{ getHealthText(recordForm.health_status) }}</text>
              <uni-icons type="right" size="14" color="#cccccc"></uni-icons>
            </view>
          </picker>
        </view>
      </view>
      
      <!-- 环境数据 -->
      <view class="form-section">
        <view class="section-title">
          <text>环境数据</text>
        </view>
        
        <view class="form-item">
          <text class="form-label">温度(°C)</text>
          <input 
            class="form-input" 
            v-model="recordForm.temperature" 
            type="digit"
            placeholder="请输入温度"
          />
        </view>
        
        <view class="form-item">
          <text class="form-label">湿度(%)</text>
          <input 
            class="form-input" 
            v-model="recordForm.humidity" 
            type="digit"
            placeholder="请输入湿度"
          />
        </view>
        
        <view class="form-item">
          <text class="form-label">光照(lux)</text>
          <input 
            class="form-input" 
            v-model="recordForm.light" 
            type="digit"
            placeholder="请输入光照"
          />
        </view>
        
        <view class="form-item">
          <text class="form-label">土壤湿度(%)</text>
          <input 
            class="form-input" 
            v-model="recordForm.soil_moisture" 
            type="digit"
            placeholder="请输入土壤湿度"
          />
        </view>
      </view>
      
      <!-- 养护记录 -->
      <view class="form-section">
        <view class="section-title">
          <text>养护记录</text>
        </view>
        
        <view class="form-item">
          <text class="form-label">浇水</text>
          <switch 
            :checked="recordForm.watering" 
            @change="onWateringChange" 
            color="#4CAF50"
          />
        </view>
        
        <view class="form-item">
          <text class="form-label">施肥</text>
          <switch 
            :checked="recordForm.fertilizing" 
            @change="onFertilizingChange" 
            color="#4CAF50"
          />
        </view>
        
        <view class="form-item">
          <text class="form-label">病虫害防治</text>
          <switch 
            :checked="recordForm.pest_control" 
            @change="onPestControlChange" 
            color="#4CAF50"
          />
        </view>
        
        <view class="form-item">
          <text class="form-label">备注</text>
          <textarea 
            class="form-textarea" 
            v-model="recordForm.notes" 
            placeholder="请输入备注信息"
            maxlength="500"
          />
        </view>
      </view>
      
      <!-- 图片上传 -->
      <view class="form-section">
        <view class="section-title">
          <text>图片记录</text>
        </view>
        
        <view class="image-upload">
          <view 
            class="upload-preview" 
            v-for="(img, index) in recordForm.images" 
            :key="index"
          >
            <image :src="img" mode="aspectFill"></image>
            <view class="remove-image" @tap="removeImage(index)">
              <uni-icons type="close" size="16" color="#ffffff"></uni-icons>
            </view>
          </view>
          
          <view class="upload-btn" @tap="chooseImage" v-if="recordForm.images.length < 6">
            <uni-icons type="camera" size="24" color="#999999"></uni-icons>
            <text>上传图片</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 加载中 -->
    <view class="loading" v-else>
      <text>加载中...</text>
    </view>
    
    <!-- 底部按钮 -->
    <view class="bottom-buttons">
      <view class="cancel-btn" @tap="goBack">
        <text>取消</text>
      </view>
      <view class="save-btn" @tap="saveRecord">
        <text>保存</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
/// <reference types="@dcloudio/types" />
import { ref, reactive, computed, onMounted } from 'vue';
import uniIcons from '@/uni_modules/uni-icons/components/uni-icons/uni-icons.vue';

// 是否为编辑模式
const isEdit = ref(false);
const recordId = ref('');
const cropId = ref('');
const cropName = ref('未知农作物');
const formLoaded = ref(false);

// 记录表单数据
const recordForm = reactive({
  crop_id: '',
  record_date: null,
  growth_stage: '',
  height: '',
  leaf_count: '',
  health_status: 2,
  watering: false,
  fertilizing: false,
  pest_control: false,
  temperature: '',
  humidity: '',
  light: '',
  soil_moisture: '',
  notes: '',
  images: []
});

// 生长阶段选项
const growthStages = [
  '种子期',
  '发芽期',
  '幼苗期',
  '生长期',
  '开花期',
  '结果期',
  '成熟期'
];

// 健康状况选项
const healthOptions = [
  { value: 0, label: '不佳', class: 'health-poor' },
  { value: 1, label: '一般', class: 'health-fair' },
  { value: 2, label: '良好', class: 'health-good' },
  { value: 3, label: '优秀', class: 'health-excellent' }
];

// 选择器索引
const growthStageIndex = computed(() => {
  const index = growthStages.findIndex(item => item === recordForm.growth_stage);
  return index >= 0 ? index : 0;
});

const healthIndex = computed(() => {
  const index = healthOptions.findIndex(item => item.value === recordForm.health_status);
  return index >= 0 ? index : 2;
});

// 日期格式化
const formatDateToStr = (timestamp) => {
  if (!timestamp) return '';
  const date = new Date(timestamp);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

// 日期字符串
const recordDateStr = computed(() => formatDateToStr(recordForm.record_date));

// 获取页面参数
const getPageParams = () => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  return currentPage.$page?.options || {};
};

// 初始化表单
const initForm = async () => {
  formLoaded.value = false;
  
  try {
    const params = getPageParams();
    recordId.value = params.id;
    cropId.value = params.crop_id;
    
    if (!cropId.value) {
      uni.showToast({
        title: '参数错误',
        icon: 'none'
      });
      goBack();
      return;
    }
    
    // 获取农作物信息
    await getCropInfo();
    
    if (recordId.value) {
      // 编辑模式
      isEdit.value = true;
      await getRecordDetail();
    } else {
      // 添加模式
      isEdit.value = false;
      recordForm.crop_id = cropId.value;
      recordForm.record_date = Date.now();
      recordForm.images = [];
      formLoaded.value = true;
    }
  } catch (error) {
    console.error('初始化表单失败:', error);
    uni.showToast({
      title: '加载失败',
      icon: 'none'
    });
    goBack();
  }
};

// 获取农作物信息
const getCropInfo = async () => {
  try {
    const { result } = await uniCloud.callFunction({
      name: 'crop',
      data: {
        action: 'get',
        data: {
          id: cropId.value
        }
      }
    });
    
    if (result.code === 200) {
      cropName.value = result.data.name;
    }
  } catch (error) {
    console.error('获取农作物信息失败:', error);
  }
};

// 获取记录详情
const getRecordDetail = async () => {
  try {
    const { result } = await uniCloud.callFunction({
      name: 'crop-record',
      data: {
        action: 'get',
        data: {
          id: recordId.value
        }
      }
    });
    
    if (result.code === 200) {
      // 填充表单数据
      Object.assign(recordForm, result.data);
      
      // 确保images是数组
      if (!recordForm.images) {
        recordForm.images = [];
      }
      
      formLoaded.value = true;
    } else {
      uni.showToast({
        title: result.msg,
        icon: 'none'
      });
      goBack();
    }
  } catch (error) {
    console.error('获取记录详情失败:', error);
    uni.showToast({
      title: '获取数据失败',
      icon: 'none'
    });
    goBack();
  }
};

// 选择记录日期
const onRecordDateChange = (e) => {
  recordForm.record_date = new Date(e.detail.value).getTime();
};

// 选择生长阶段
const onGrowthStageChange = (e) => {
  const index = e.detail.value;
  recordForm.growth_stage = growthStages[index];
};

// 选择健康状况
const onHealthChange = (e) => {
  const index = e.detail.value;
  recordForm.health_status = healthOptions[index].value;
};

// 浇水开关
const onWateringChange = (e) => {
  recordForm.watering = e.detail.value;
};

// 施肥开关
const onFertilizingChange = (e) => {
  recordForm.fertilizing = e.detail.value;
};

// 病虫害防治开关
const onPestControlChange = (e) => {
  recordForm.pest_control = e.detail.value;
};

// 获取健康状况文本
const getHealthText = (health) => {
  const option = healthOptions.find(item => item.value === health);
  return option ? option.label : '未知';
};

// 获取健康状况类名
const getHealthClass = (health) => {
  const option = healthOptions.find(item => item.value === health);
  return option ? option.class : '';
};

// 选择图片
const chooseImage = () => {
  uni.chooseImage({
    count: 6 - recordForm.images.length,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      // 上传图片到云存储
      const uploadTasks = res.tempFilePaths.map((tempFilePath, index) => {
        return new Promise((resolve, reject) => {
          // 使用文件原始名称作为cloudPath
          const cloudPath = res.tempFiles[index].name;
          
          uni.showLoading({ title: '上传中...' });
          
          uniCloud.uploadFile({
            filePath: tempFilePath,
            cloudPath: cloudPath,
            success: (uploadRes) => {
              console.log('上传成功', uploadRes);
              resolve(uploadRes.fileID);
            },
            fail: (err) => {
              console.error('上传失败', err);
              reject(err);
            }
          });
        });
      });
      
      Promise.all(uploadTasks)
        .then(fileIDs => {
          // 添加所有上传成功的图片ID到记录中
          recordForm.images = [...recordForm.images, ...fileIDs];
        })
        .catch(err => {
          uni.showToast({
            title: '部分图片上传失败',
            icon: 'none'
          });
        })
        .finally(() => {
          uni.hideLoading();
        });
    }
  });
};

// 移除图片
const removeImage = (index) => {
  recordForm.images.splice(index, 1);
};

// 表单验证
const validateForm = () => {
  if (!recordForm.record_date) {
    uni.showToast({
      title: '请选择记录日期',
      icon: 'none'
    });
    return false;
  }
  
  if (!recordForm.growth_stage) {
    uni.showToast({
      title: '请选择生长阶段',
      icon: 'none'
    });
    return false;
  }
  
  return true;
};

// 保存记录
const saveRecord = async () => {
  if (!validateForm()) return;
  
  try {
    uni.showLoading({
      title: '保存中...'
    });
    
    // 处理数值类型
    const data = { ...recordForm };
    
    if (data.height) {
      data.height = parseFloat(data.height);
    }
    
    if (data.leaf_count) {
      data.leaf_count = parseInt(data.leaf_count);
    }
    
    if (data.temperature) {
      data.temperature = parseFloat(data.temperature);
    }
    
    if (data.humidity) {
      data.humidity = parseFloat(data.humidity);
    }
    
    if (data.light) {
      data.light = parseFloat(data.light);
    }
    
    if (data.soil_moisture) {
      data.soil_moisture = parseFloat(data.soil_moisture);
    }
    
    const action = isEdit.value ? 'update' : 'add';
    
    if (isEdit.value) {
      data._id = recordId.value;
    }
    
    const { result } = await uniCloud.callFunction({
      name: 'crop-record',
      data: {
        action,
        data
      }
    });
    
    if (result.code === 200) {
      uni.showToast({
        title: isEdit.value ? '更新成功' : '添加成功',
        icon: 'success'
      });
      
      // 延迟返回上一页
      setTimeout(() => {
        goBack();
      }, 1500);
    } else {
      uni.showToast({
        title: result.msg,
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('保存记录失败:', error);
    uni.showToast({
      title: '保存失败',
      icon: 'none'
    });
  } finally {
    uni.hideLoading();
  }
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 生命周期钩子
onMounted(() => {
  initForm();
});
</script>

<style>
/* 全局样式 */
page {
  background-color: #f5f7fa;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, sans-serif;
}

.container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  padding-bottom: 80px;
  padding-top: 10px; /* 添加顶部内边距 */
}

/* 表单容器 */
.form-container {
  flex: 1;
  padding: 10px;
}

/* 表单分区 */
.form-section {
  background-color: #ffffff;
  border-radius: 8px;
  margin-bottom: 10px;
  overflow: hidden;
}

.section-title {
  padding: 10px 15px;
  border-bottom: 1px solid #f0f0f0;
}

.section-title text {
  font-size: 16px;
  font-weight: bold;
  color: #333333;
}

/* 表单项 */
.form-item {
  display: flex;
  padding: 12px 15px;
  border-bottom: 1px solid #f0f0f0;
}

.form-item:last-child {
  border-bottom: none;
}

.form-label {
  width: 120px;
  font-size: 14px;
  color: #666666;
  padding-top: 2px;
}

.required:after {
  content: '*';
  color: #ff4d4f;
  margin-left: 2px;
}

.form-value {
  flex: 1;
  font-size: 14px;
  color: #333333;
  text-align: right;
}

.form-input {
  flex: 1;
  height: 24px;
  font-size: 14px;
  color: #333333;
  text-align: right;
}

.form-textarea {
  flex: 1;
  height: 80px;
  font-size: 14px;
  color: #333333;
  text-align: right;
}

.picker {
  flex: 1;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.picker text:first-child {
  font-size: 14px;
  color: #333333;
  margin-right: 5px;
}

.picker .iconfont {
  font-size: 14px;
  color: #cccccc;
}

/* 健康状况颜色 */
.health-poor {
  color: #F44336 !important;
}

.health-fair {
  color: #FF9800 !important;
}

.health-good {
  color: #4CAF50 !important;
}

.health-excellent {
  color: #2196F3 !important;
}

/* 图片上传 */
.image-upload {
  padding: 15px;
  display: flex;
  flex-wrap: wrap;
}

.upload-btn {
  width: 100px;
  height: 100px;
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-right: 10px;
  margin-bottom: 10px;
}

.upload-btn .iconfont {
  font-size: 24px;
  color: #999999;
  margin-bottom: 8px;
}

.upload-btn text:last-child {
  font-size: 14px;
  color: #999999;
}

.upload-preview {
  position: relative;
  width: 100px;
  height: 100px;
  border-radius: 8px;
  overflow: hidden;
  margin-right: 10px;
  margin-bottom: 10px;
}

.upload-preview image {
  width: 100%;
  height: 100%;
}

.remove-image {
  position: absolute;
  top: 0;
  right: 0;
  width: 24px;
  height: 24px;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 0 0 0 8px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.remove-image .iconfont {
  font-size: 16px;
  color: #ffffff;
}

/* 加载中 */
.loading {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading text {
  font-size: 14px;
  color: #999999;
}

/* 底部按钮 */
.bottom-buttons {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  height: 60px;
  background-color: #ffffff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}

.cancel-btn, .save-btn {
  flex: 1;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cancel-btn {
  background-color: #f5f5f5;
}

.cancel-btn text {
  font-size: 16px;
  color: #666666;
}

.save-btn {
  background-color: #4CAF50;
}

.save-btn text {
  font-size: 16px;
  color: #ffffff;
}

/* 图标样式 */
.iconfont {
  font-family: "iconfont";
}

.icon-back:before {
  content: "\e679";
}

.icon-right:before {
  content: "\e6a3";
}

.icon-camera:before {
  content: "\e6ac";
}

.icon-close:before {
  content: "\e69e";
}
</style> 